<template>
  <div class="index-contain">
    <div class="navbar">
      <div class="search">
        <i class="i-search"></i>
        <input
          type="text"
          class="inpt-search"
          @click="handleSearch"
          :placeholder="placeholder"
        />
      </div>
      <!-- <div class="user-center" @click="handleUserCenter">
        <i class="i-user"></i>
        <span>个人中心</span>
      </div> -->
    </div>
    <div class="banner">
    </div>
    <div class="banner-panel">
      <van-swipe class="banner-panel-swipe" :height="160" :autoplay="4000">
        <van-swipe-item
          style="margin: 0 auto;text-align: center;position: relative"
          v-for="image in bannerList"
        >
          <img :src="image.src" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="header-category">
      <div class="header-category__items" v-for="val in categoryRows">
        <div
          class="item"
          v-if="categoryList[5 * (val - 1)]"
          @click="handleCategory(categoryList[5 * (val - 1)])"
        >
          <img :src="categoryList[5 * (val - 1)].picUrl" />
          <div class="text">{{ categoryList[5 * (val - 1)].name }}</div>
        </div>
        <div
          class="item"
          v-if="categoryList[5 * (val - 1) + 1]"
          @click="handleCategory(categoryList[5 * (val - 1) + 1])"
        >
          <img :src="categoryList[5 * (val - 1) + 1].picUrl" />
          <div class="text">{{ categoryList[5 * (val - 1) + 1].name }}</div>
        </div>
        <div
          class="item"
          v-if="categoryList[5 * (val - 1) + 2]"
          @click="handleCategory(categoryList[5 * (val - 1) + 2])"
        >
          <img :src="categoryList[5 * (val - 1) + 2].picUrl" />
          <div class="text">{{ categoryList[5 * (val - 1) + 2].name }}</div>
        </div>
        <div
          class="item"
          v-if="categoryList[5 * (val - 1) + 3]"
          @click="handleCategory(categoryList[5 * (val - 1) + 3])"
        >
          <img :src="categoryList[5 * (val - 1) + 3].picUrl" />
          <div class="text">{{ categoryList[5 * (val - 1) + 3].name }}</div>
        </div>
        <div
          class="item"
          v-if="categoryList[5 * (val - 1) + 4]"
          @click="handleCategory(categoryList[5 * (val - 1) + 4])"
        >
          <img :src="categoryList[5 * (val - 1) + 4].picUrl" />
          <div class="text">{{ categoryList[5 * (val - 1) + 4].name }}</div>
        </div>
      </div>
    </div>
    <div class="contain">
      <div class="contain-spike">
        <div class="contain-spike__header">
          <span>限量秒杀</span>
          <span @click="goSpike">更多></span>
        </div>
        <div class="contain-spike__content">
          <div
            class="contain-spike__content__item"
            v-for="val in spikeList"
            @click="handleDetail(val.id, 1)"
          >
            <img :src="val.thumb" />
            <div>￥{{ val.price }}</div>
          </div>
          <!--<div class="contain-spike__content__item">-->
          <!--<img src="../../assets/images/1.png">-->
          <!--<div>￥1000</div>-->
          <!--</div>-->
          <!--<div class="contain-spike__content__item">-->
          <!--<img src="../../assets/images/1.png">-->
          <!--<div>￥10000</div>-->
          <!--</div>-->
          <!--<div class="contain-spike__content__item">-->
          <!--<img src="../../assets/images/1.png">-->
          <!--<div>￥10000</div>-->
          <!--</div>-->
        </div>
      </div>
      <filterbar @range-result="handleRange" @filter-result="handleFilter" @order-result="handleGoodsSort"></filterbar>
      <ul class="goods-list" :class="range===1? 'list-double': ''">
        <van-pull-refresh v-model="isDownLoading" @refresh="onRefresh">
          <van-list
            v-model="isUploading"
            :finished="finished"
            :finished-text="finished_text"
            @load="onLoad"
            :offset="10"
          >
            <li class="goods-list-item" v-for="val in list" @click="handleDetail(val.id, 0)">
              <div class="goods-list-item__thumb">
                <img v-lazy="imageShow(val.primary_pic_url)" />
              </div>
              <div class="goods-list-item__content">
                  <div class="title">{{ val.name }}</div>
                  <div class="discount">
                      <img :src="sendBdcUrl" />
                  </div>
                  <div class="price">￥{{ val.retail_price }}</div>
                  <div class="salse">
                      <div class="salse-left">
                      <span><del>￥{{ val.market_price }}</del></span>
                      <span class="tag">包邮</span>
                      </div>
                      <span>已售{{ val.sell_volume ? val.sell_volume : 0 }}件</span>
                  </div>
              </div>
            </li>
          </van-list>
        </van-pull-refresh>  
      </ul>
      <!-- <div class="contain-goods">
        <van-pull-refresh v-model="isDownLoading" @refresh="onRefresh">
          <van-list
            v-model="isUploading"
            :finished="finished"
            :finished-text="finished_text"
            @load="onLoad"
            :offset="10"
          >
            <div
              class="contain-goods__item"
              v-for="val in list"
              @click="handleDetail(val.id, 0)"
            >
              <div class="contain-goods__item__left">
                <img v-lazy="imageShow(val.primary_pic_url)" />
              </div>
              <div class="contain-goods__item__right">
                <div class="title">{{ val.name }}</div>
                <div class="discount-icon">
                  <img :src="sendBdcUrl" />
                </div>
                <div class="discount">
                  <span
                    ><span class="money">￥</span
                    >{{
                      val.promotionalPrice
                        ? val.promotionalPrice
                        : val.retail_price
                    }}</span
                  >
                  <span class="discount-tag" v-if="val.promotionalPrice"
                    >{{ val.promotionalDiscount }}折价</span
                  >
                </div>
                <div class="merge" v-if="val.fightGroupPrice">
                  <span
                    ><span class="money">￥</span
                    >{{ val.fightGroupPrice }}</span
                  >
                  <span class="merge-tag">折后拼单价</span>
                </div>
                <div class="salse">
                  <div class="salse-left">
                    <span v-if="val.promotionalPrice"
                      ><del>￥{{ val.retail_price }}</del></span
                    >
                    <span v-else>
                      <del>￥{{ val.market_price }}</del>
                    </span>
                    <span class="tag">包邮</span>
                  </div>
                  <span>已售{{ val.sell_volume ? val.sell_volume : 0 }}件</span>
                </div>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div> -->
    </div>
    <footerbar></footerbar>
    <div class="show-box" v-if="showBox">
        <div class="binding">
          <div class="binding-header">
            <div class="space"></div>
            <div class="title">绑定手机</div>
            <div class="space"></div>
            <!-- <i class="i-close" @click="handleClose"></i> -->
          </div>
          <div class="form">
            <div class="form-item">
                <i class="i-b-phone"></i>
                <input type="number" v-model="form.telephone" class="inpt" placeholder="请填写您的手机号码" @focus="handleFocus('telephone')" />
            </div>
            <div class="err-message" v-if="errorMsg.telephone">{{errorMsg.telephone}}</div>
            <div class="form-item">
              <div class="form-item__left">
                <i class="i-b-code"></i>
                <input type="number" v-model="form.randcode"  class="inpt h-p-80" placeholder="请输入手机验证码" @focus="handleFocus('randcode')" />
              </div>
             <button v-show="show" class="btn-send" :disabeld="btnDisabld" @click="handleSendMessage">获取验证码</button>
             <button v-show="!show" v-if="count>=10" class="btn-send">{{count}} s</button>
             <button v-show="!show" v-else-if="count<10" class="btn-send">0{{count}} s</button>
            </div>
            <div class="err-message" v-if="errorMsg.randcode">{{errorMsg.randcode}}</div>
            <div class="form-item">
                <i class="i-b-msg"></i>
                <input type="text" v-model="form.recommendCode"  :readonly="disabled" class="inpt" placeholder="请填写用户邀请码" />
            </div>
            <div class="err-message" v-if="errorMsg.recommendCode">{{errorMsg.recommendCode}}</div>
            <div class="tips">已注册用户无需填写邀请码</div>
            <button class="btn-binding" @click="handleBinding">确定</button>
          </div>
        </div>
        <div></div>
    </div>
    <div class="show-box-overlay" v-if="showBox"></div>
  </div>
</template>

<script>
import filterbar from "@/components/filterbar" 
import footerbar from "@/components/footerbar"  
import { Dialog } from 'vant'  
import validator from '@/utils/validator'
import { getUserInfo,getCode, userBinding } from "@/api/bdchats"
import { getBanners, getCategory, getGoodsSpike, getGoodsList} from '@/api/goods'
import { authorizedLogin } from "@/utils"
import { validateMobile } from "@/utils/rule"

export default {
  name: "index",
  components: { filterbar, footerbar },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validateMobile(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    };
    return {
      range: 1,
      show: true,
      timer: null,
      count: 0,
      second: 60,
      btnDisabld: false,
      showBox: false,
      openid: '',
      placeholder: "金丝玉",
      isDownLoading: false,
      isUploading: false,
      finished: false,
      finished_text: "没有更多了",
      list: [],
      totalPages: 1,
      isFirst: true,
      query: {
        page: 1,
        limit: 10,
        cIds: '',
        minPrice: '',
        maxPrice: '',
        sidx: "id",
        order:'desc',
      },
      bannerList: [],
      categoryRows: 0,
      categoryList: [],
      spikeList: [],
      sendBdcUrl: "https://images.bdchats.com/prod/upload/product_discount.png",
      reg: /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/,
      disabled: false,
      form: {
        telephone: '',
        randcode: '',
        recommendCode: ''
      },
      rules: {
        telephone:[{validator: validatePhone, message: '请输入正确的手机号码'}],
        randcode: [{required: true, message: '请输入手机验证码'}]
      },
      errorMsg: {
        telephone: '',
        randcode: '',
        recommendCode: ''
      },
    };
  },
  created() {    
    // localStorage.clear()
    // this.$cookies.set("openid", 'oTw1H58r5hYBlD1YqWHEV__kQC6w', 60 * 60 * 24 * 7) 
    // this.$cookies.set("userId", '10000154', 60 * 60 * 24 * 7) 
    // this.$cookies.set("token", 'da66f6783c964d719af8a516042cd7ce', 60 * 60 * 24 * 7) 
    // this.$cookies.set("expires_in",1596265707,60 * 60 * 24 * 7) 
    let userid = 0
    let access_token = ''
    if(this.$route.query) {
      this.openid = this.$route.query.openid
      if(this.openid ) {
        if(this.openid) {
          // localStorage.setItem('openid',this.$route.query.openid)
          this.$cookies.set("openid",this.$route.query.openid,60 * 60 * 24 * 7) //有效期7天
        }
      }
      userid = this.$route.query.userId
      if(userid) {
        // localStorage.setItem('userId', userid)
        this.$cookies.set("userId",userid, 60 * 60 * 24 * 7) //有效期7天
      }
      access_token = this.$route.query.access_token
      if(access_token) {
        // localStorage.setItem('token', access_token)
        this.$cookies.set("token",access_token,60 * 60 * 24 * 7) //有效期7天
      }
      if(userid && access_token) {
        const expiresIn = (new Date()).getTime() + 3600 * 24 * 1000 * 30
        // localStorage.setItem('expires_in', parseInt(expiresIn/1000) )
        this.$cookies.set("expires_in",parseInt(expiresIn/1000),60 * 60 * 24 * 7) 
      }
      if(this.$route.query.recommendCode && this.$route.query.recommendCode!="undefined") {
        this.form.recommendCode = this.$route.query.recommendCode
        this.disabled = true
      }
    }
    let url = process.env.VUE_APP_BDCHATS_API + '/weixin/auth/login?webCallBack=' + window.location.protocol + '//' + window.location.host 
    if(!this.$cookies.get('openid') || this.$cookies.get('openid')==='undefined' || this.$cookies.get('openid')===undefined) { 
      window.location.href = url
    } else {
      if(this.$cookies.get('userId') === undefined || this.$cookies.get('userId')=== 'undefined') {
        window.location.href = url
      }
      if(this.$cookies.get('token') === undefined || this.$cookies.get('token')=== 'undefined') {
        window.location.href = url
      }
    }
    // console.log(window.location.href)
    // alert( window.location.href)
    // alert(localStorage.getItem('openid'))
    // alert(localStorage.getItem('userId'))
    // alert(localStorage.getItem('token'))

    
    if(this.$cookies.get('openid') && this.$cookies.get('openid') !== 'undefined'){
      if(!this.$cookies.get('userId') || !this.$cookies.get('token')){
        if(userid && access_token && userid != "0" && access_token !='' && userid != 0 && !localStorage.getItem('expires_in')) {
          // localStorage.setItem('userId', userid)
          // localStorage.setItem('token', access_token)
          const expiresIn = (new Date()).getTime() + 3600 * 24 * 1000 * 30
          // localStorage.setItem('expires_in', parseInt(expiresIn/1000) )


          this.$cookies.set("userId", userid, 60 * 60 * 24 * 7) 
          this.$cookies.set("token", access_token, 60 * 60 * 24 * 7) 
          this.$cookies.set("expires_in",parseInt(expiresIn/1000),60 * 60 * 24 * 7) 
          this.isBinding()
        } else {
          this.showBox = true
        }
      }
    } else {
      window.location.href = url
    }
    if(this.$cookies.get('userId') && this.$cookies.get('userId') != 0 && this.$cookies.get('token') && this.$cookies.get('token')!="") {
      this.query.page = 0
      // this.totalPages = 0
      this.getBannersList();
      this.getCategoryList();
      this.getSpikeList();
    }
    this.validator = validator(this.rules, this.form);
    sessionStorage.setItem('catePid', '')
  },
  methods: {
    handleClose() {
      this.showBox = false
    },
    isBinding() {
      getUserInfo().then(response=>{
        if(!response.data) { 
          if(!response.data.openid) {
            this.showBox = true
          }
        }
      })
    },
    handleFocus(type) {
      if(type === "telephone") {
        this.errorMsg.telephone = ""
      } else if(type === "randcode") {
        this.errorMsg.randcode = ""
      }
    },
    handleUserCenter() {
      this.$router.push("/user/center");
    },
    handleSearch() {
      sessionStorage.setItem("searchText", this.placeholder);
      this.$router.push("/search");
    },
    goSpike() {
      this.$router.push("/spike/list");
    },
    getBannersList() {
      const self = this;
      const data = {};
      data.page = 1;
      data.limit = 10;
      data.ad_position_id = 1;
      getBanners(data).then(response => {
        if (response.errno === 0 && response.data && response.data.pageUtil) {
          const dataList = response.data.pageUtil.list;
          for (const item of dataList) {
            const temp = {};
            temp.loading = require("@/assets/images/loading.gif");
            temp.src = item.image_url;
            temp.url = item.link;
            self.bannerList.push(temp);
          }
        }
      });
    },
    getCategoryList() {
      const self = this;
      const data = {};
      (data.level = "L1"), (data.page = 1);
      data.limit = 10;
      data.sidx = "";
      data.parentId = 0;
      getCategory(data).then(response => {
        if (response.data && response.data.length > 0) {
          for (const item of response.data) {
            if (item.level === "L1") {
              const temp = {};
              temp.id = item.id;
              temp.name = item.name;
              temp.picUrl = item.picUrl;
              temp.type = item.type;
              self.categoryList.push(temp);
            }
          }
          // const all = {}
          // all.id = 0
          // all.name = '全部'
          // all.picUrl = 'https://images.bdchats.com/prod/upload/category/all.png'
          // self.categoryList.push(all)
          self.categoryRows = Math.ceil(self.categoryList.length / 5);
        }
      });
    },
    handleCategory(category) {
        sessionStorage.setItem("categoryId", category.id);
        sessionStorage.setItem("catePid", category.id);
        sessionStorage.setItem("categoryName", category.name);
        this.$router.push("/list");
    },
    getSpikeList() {
      const self = this;
      const data = {};
      data.page = 1;
      data.sidx = "";
      data.limit = 4;
      getGoodsSpike(data).then(response => {
        if (response.data.spikePage.list) {
          for (const item of response.data.spikePage.list) {
            const temp = {};
            temp.id = item.id;
            temp.thumb = item.primary_pic_url;
            temp.price = item.retail_price;
            self.spikeList.push(temp);
          }
        }
      });
    },
    handleDetail(id, isSpike) {
      sessionStorage.setItem("isSpike", isSpike);
      this.$router.push("/detail/" + id);
    },
    imageShow(src) {
      const img = {};
      img.loading = require("@/assets/images/loading.gif");
      img.src = src;
      return img;
    },
    async getList() {
      await getGoodsList(this.query).then(response => {
        if (this.isFirst) {
          this.isFirst = false;
          this.totalPages = response.data.pageUtil.totalPage;
        }
        if (this.list.length) {
          if (this.isUploading) {
            //上拉加载
            for (const item of response.data.pageUtil.list) {
              this.list.push(item);
            }
            this.$nextTick(() => {
              this.isUploading = false;
            });
            if (this.list.length >= response.data.pageUtil.totalCount) {
              this.finished = true;
            }
          }

          if (this.isDownLoading) {
            //关闭下拉刷新
            this.isDownLoading = false;
            this.list = [];
            for (const item of response.data.pageUtil.list) {
              this.list.push(item);
            }
            if (this.finished) {
              this.finished = false;
            }
          }
        } else {
          if (response.data.pageUtil && response.data.pageUtil.list) {
            const dataList = response.data.pageUtil.list;
            for (const item of dataList) {
              this.list.push(item);
            }
            if (response.data.pageUtil.totalCount === 0) {
              this.finished_text = "暂无数据";
              this.finished = true;
            }
          }
          this.isUploading = false;
          this.isDownLoading = false;
        }
      });
    },
    onLoad() {
      if(this.query.page < this.totalPages) {
        this.query.page = this.query.page + 1
        this.isUploading = true
        this.getList()
      }else{
        this.finished = true
        this.isDownLoading = false
        this.isUploading = false
      }
    },
    onRefresh() {
      this.finished = false;
      this.isUploading = false;
      this.totalPages = 0
      this.query.page = 1
      this.list = []
      this.getList();
    },
    handleSendMessage() {
      this.btnDisabld = true
      if (!this.reg.test(this.form.telephone) || !this.form.telephone) {
        this.errorMsg.telephone = '请输入正确的手机号码'
        return
      }
      const data = {}
      data.areaCode = 86
      data.telephone = this.form.telephone
      data.isRegister = 2
      getCode(data).then(response => {
        this.btnDisabld = false
        if (response && response.resultCode && response.resultCode === 1) {
          if (!this.timer) {
            this.count = this.second
            this.show = false
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= this.second) {
                this.count--
              } else {
                this.show = true
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
          }
        }
      })
      
    },
    handleBinding() {
      const self = this
      this.validate((errors, fields) => {
        if (errors === false) {
          const data = {}
          data.areaCode = 86
          data.telephone = this.form.telephone
          data.randcode = this.form.randcode
          data.recommendCode = this.form.recommendCode
          data.openid = this.openid ? this.openid : localStorage.getItem('openid') 
          userBinding(data).then(response =>{
            if(response.resultCode===1) {
              Dialog.alert({
                title: "",
                message: response.resultMsg
              }).then(() => {
                this.showBox = false
                const expiresIn = (new Date()).getTime() + 3600 * 24 * 1000 * 30
                this.$cookies.set("userId", response.data.userId, 60 * 60 * 24 * 7) 
                this.$cookies.set("token", response.data.access_token, 60 * 60 * 24 * 7) 
                this.$cookies.set("expires_in",parseInt(expiresIn/1000),60 * 60 * 24 * 7) 

                this.getBannersList();
                this.getCategoryList();
                this.getSpikeList();
                this.totalPages = 0
                this.query.page = 1
                this.getList()
              })
            } else {
              Dialog.alert({
                title: "",
                message: response.resultMsg
              }).then(()=> {
                this.showBox = false
              })
            }
          });
        }
      })
    },
    /**
      * 清除验证提示
      * @param attrs
    */
    resetField(attrs) {
      attrs = !attrs ? Object.keys(this.errorMsg) : ( Array.isArray(attrs) ? attrs : [attrs]);
      attrs.forEach(attr => {
        this.errorMsg[attr] = ''
      })
    },
    /**
      * 验证方法
      * @param callback
      * @param data
    */
    validate(callback, data) {
      const self = this
      this.validator.validate((errors, fields) => {
        this.resetField();
        if (errors) {
          fields.forEach(item => {
            self.errorMsg[item.field] = item.message
          })
        }
        callback && callback(errors, fields)
      }, data);
    },
    handleRange(range){
      this.range = range
    },
    handleFilter(data) {
       if(data) {
        this.list = []
        this.totalPages = 0
        this.query.page = 1
        this.query.minPrice = data.minPrice
        this.query.maxPrice = data.maxPrice
        this.query.cIds = data.cIds
        this.finished = false;
        this.isUploading = false;
        this.getList()
      
      }
    },
    handleGoodsSort(data) {
      if(data) {
        this.list = []
        this.totalPages = 0
        this.query.page = 1
        this.query.sidx = data.sidx
        this.query.order = data.sort
        this.finished = false;
        this.isUploading = false;
        this.getList()
      }
    }
  }
};
</script>

